﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using D2DEngine.Util;

namespace D2DEngine.Tile
{
    public class D2DTileSet
    {
        protected Texture2D texture;
        protected int tileSize;


        /// <summary>
        /// The size of one tile in the tile map
        /// in width and height. Tiles are always squares.
        /// </summary>
        public int TileSize
        {
            get { return this.tileSize; }
            set { this.tileSize = value; }
        }

        /// <summary>
        /// The texture representing the tileset
        /// of the whole map
        /// </summary>
        public Texture2D Texture
        {
            get { return this.texture; }
            set { this.texture = value; }
        }

        /// <summary>
        /// The tile set's width in cells
        /// </summary>
        public int WidthInCells
        {
            get { return this.texture.Width / this.tileSize; }
        }

        /// <summary>
        /// The tile set's height in cells
        /// </summary>
        public int HeightInCells
        {
            get { return this.texture.Height / this.tileSize; }
        }

        public D2DTileSet(Texture2D texture)
        {
            this.texture = texture;
        }

        /// <summary>
        /// Gets the source rectangle of the tile represented
        /// by the index specified in parameter.
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public Rectangle GetSourceRectangle(int index)
        {
            int row;
            int column;

            if (index % WidthInCells == 0)
            {
                row = index / WidthInCells;
                column = WidthInCells;
            }
            else
            {
                row = D2DMath.DivisionCeiling(index, WidthInCells);
                column = index % WidthInCells;
            }

            return new Rectangle(
                    (column - 1)  * this.tileSize,
                    (row - 1)  * this.tileSize,
                    this.tileSize,
                    this.tileSize
                );
        }

    }
}
